package mwt.xml.xdbforms.dbms.impl;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import mwt.xml.xdbforms.dbms.metadata.MetadataManager;
import mwt.xml.xdbforms.dbms.XDBFManager;
import mwt.xml.xdbforms.dbms.metadata.impl.MySQLMetadataManager;
import mwt.xml.xdbforms.dbms.query.QueryManager;
import mwt.xml.xdbforms.dbms.query.impl.MySQLQueryManager;
import mwt.xml.xdbforms.xforms.XFormsModelManager;
import mwt.xml.xdbforms.xforms.XFormsUIManager;
import mwt.xml.xdbforms.xforms.impl.XFormsModelManagerImpl;
import mwt.xml.xdbforms.xforms.impl.XFormsUIManagerImpl;

public class MySqlXDBFManager extends XDBFManager {
    private Connection connection = null;
    private String url = null;

    public MySqlXDBFManager(InputStream is) throws IOException, ClassNotFoundException {
        Properties props = new Properties();
        props.load(is);

        this.url = props.getProperty("database.url");
        Class.forName(props.getProperty("database.driver"));
    }

    @Override
    public boolean connect(String username, String password) {
        try {
            this.connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException ex) {
            Logger.getLogger(MySqlXDBFManager.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }

        return true;
    }

    @Override
    public void disconnect() {
        if (this.connection != null) {
            try {
                this.connection.close();
            } catch (SQLException ex) {
                Logger.getLogger(MySqlXDBFManager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public QueryManager getQueryManager() {
        return new MySQLQueryManager(this.connection);
    }

    @Override
    public MetadataManager getMetadataManager() {
        return new MySQLMetadataManager(this.connection);
    }

    @Override
    public XFormsModelManager getXFormsModelManager() throws ParserConfigurationException {
        return new XFormsModelManagerImpl();
    }

    @Override
    public XFormsUIManager getXFormsUIManager() throws ParserConfigurationException {
        return new XFormsUIManagerImpl();
    }
}